<template>
  <div class="announcement-management">
    <!-- 搜索和操作区域 -->
    <div class="search-operation">
      <el-card shadow="never">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="公告标题">
              <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
              <el-button @click="handleReset" :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 公告列表 -->
    <div class="announcement-list">
      <el-card shadow="never">
        <template #header>
          <div class="table-header">
            <span>公告列表</span>
            <div>
              <el-button type="primary" @click="handleCreate" :icon="Plus">发布公告</el-button>
              <el-button @click="handleBatchDelete" :icon="Delete" :disabled="selectedIds.length === 0">
                批量删除
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="announcementList" v-loading="loading" border stripe style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="announcement_id" label="ID" width="80" align="center" />
          <el-table-column prop="title" label="公告标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="公告内容" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.content ? row.content.substring(0, 50) + (row.content.length > 50 ? '...' : '')
                : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="admin.admin_name" label="发布者" width="120" />
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.updated_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)" :icon="Edit">
                编辑
              </el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row.announcement_id)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog v-model="formDialogVisible" :title="formTitle" width="600px" destroy-on-close>
      <el-form ref="announcementFormRef" :model="announcementForm" :rules="announcementFormRules" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="announcementForm.content" type="textarea" :rows="6" placeholder="请输入公告内容" maxlength="1000"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import {
  getAnnouncements,
  createAnnouncement,
  updateAnnouncement,
  deleteAnnouncement,
  batchDeleteAnnouncements
} from '@/api/announcement'
// 导入管理员API
import { getAdminCurrent } from '@/api/admin'

const loading = ref(false)
const formDialogVisible = ref(false)
const formLoading = ref(false)
const announcementFormRef = ref()
const currentAnnouncement = ref(null)
const announcementList = ref([])
const selectedIds = ref([])
const currentAdmin = ref(null) // 存储当前管理员信息

// 搜索表单
const searchForm = reactive({
  title: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 公告表单 - 移除 admin_id 字段，因为使用当前管理员
const announcementForm = reactive({
  title: '',
  content: ''
})

// 表单验证规则 - 移除 admin_id 的验证
const announcementFormRules = {
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 5, max: 1000, message: '内容长度在 5 到 1000 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const formTitle = computed(() => {
  return isCreate.value ? '发布公告' : '编辑公告'
})

const isCreate = computed(() => {
  return !currentAnnouncement.value?.announcement_id
})

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return dateString
  }
}

// 页面加载时获取公告列表和当前管理员信息
onMounted(() => {
  fetchAnnouncements()
  fetchCurrentAdmin()
})

// 获取当前管理员信息
const fetchCurrentAdmin = async () => {
  try {
    const response = await getAdminCurrent()
    if (response.code === 0) {
      currentAdmin.value = response.data
      console.log('当前管理员:', currentAdmin.value)
    } else {
      ElMessage.error('获取管理员信息失败:' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取当前管理员失败:', error)
    ElMessage.error('获取管理员信息失败，请检查网络连接')
  }
}

// 获取公告列表
const fetchAnnouncements = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      title: searchForm.title,
      start_date: searchForm.dateRange?.[0],
      end_date: searchForm.dateRange?.[1]
    }

    // 清理空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getAnnouncements(params)
    console.log('公告列表响应:', response)

    if (response.code === 0) {
      // 适配不同的数据结构
      if (response.data && response.data.list) {
        // 分页数据结构
        announcementList.value = response.data.list
        pagination.total = response.data.pagination?.total || 0
      } else if (Array.isArray(response.data)) {
        // 数组数据结构
        announcementList.value = response.data
        pagination.total = response.data.length
      } else {
        // 其他情况
        announcementList.value = []
        pagination.total = 0
      }
    } else {
      ElMessage.error(response.msg || '获取公告列表失败')
      announcementList.value = []
      pagination.total = 0
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('获取公告列表失败:', error)
    announcementList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索公告
const handleSearch = () => {
  pagination.page = 1
  fetchAnnouncements()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'dateRange') {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  pagination.page = 1
  fetchAnnouncements()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.page = 1
  fetchAnnouncements()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  pagination.page = newPage
  fetchAnnouncements()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.announcement_id)
}

// 新增公告
const handleCreate = () => {
  // 检查是否有管理员权限
  if (!currentAdmin.value) {
    ElMessage.warning('请先登录管理员账号')
    return
  }

  currentAnnouncement.value = null
  resetForm()
  formDialogVisible.value = true
}

// 编辑公告
const handleEdit = (announcement) => {
  currentAnnouncement.value = announcement
  // 只设置标题和内容
  announcementForm.title = announcement.title || ''
  announcementForm.content = announcement.content || ''
  formDialogVisible.value = true
}

// 删除公告
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该公告吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await deleteAnnouncement(id)
    if (response.code === 0) {
      ElMessage.success('删除公告成功')
      fetchAnnouncements()
    } else {
      ElMessage.error(response.msg || '删除公告失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除公告失败')
      console.error('删除公告失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的公告')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条公告吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await batchDeleteAnnouncements({
      ids: selectedIds.value
    })

    if (response.code === 0) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      fetchAnnouncements()
    } else {
      ElMessage.error(response.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除失败:', error)
    }
  }
}

// 提交表单（新增/编辑）
const handleSubmit = async () => {
  if (!announcementFormRef.value) return

  try {
    await announcementFormRef.value.validate()
    formLoading.value = true

    // 准备提交数据，自动添加当前管理员ID
    const submitData = {
      ...announcementForm,
      admin_id: currentAdmin.value?.admin_id
    }

    let response

    if (isCreate.value) {
      // 新增公告
      response = await createAnnouncement(submitData)
    } else {
      // 编辑公告
      response = await updateAnnouncement(currentAnnouncement.value.announcement_id, submitData)
    }

    if (response.code === 0) {
      ElMessage.success(isCreate.value ? '发布公告成功' : '更新公告成功')
      formDialogVisible.value = false
      fetchAnnouncements()
    } else {
      ElMessage.error(response.msg || (isCreate.value ? '发布公告失败' : '更新公告失败'))
    }
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error(isCreate.value ? '发布公告失败' : '更新公告失败')
      console.error('表单提交失败:', error)
    }
  } finally {
    formLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  announcementForm.title = ''
  announcementForm.content = ''

  if (announcementFormRef.value) {
    announcementFormRef.value.clearValidate()
  }
}
</script>

<style scoped>
.announcement-management {
  padding: 20px;
}

.search-operation {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.announcement-list {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>